﻿using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using Provausio.Server.Nzb.Poller.Object.Client;
using RestSharp;

namespace Provausio.Server.Nzb.Poller.Data.Source
{
    public abstract class PingApiOperationBase
    {
        protected NameValueCollection Config
        {
            get { return ConfigurationManager.AppSettings; }
        }

        public string ServiceName { get; protected set; }
        protected abstract string ApiUri { get; }
        protected abstract string ApiFormat { get; }

        protected List<KeyValuePair<string, object>> Parameters { get; set; } 

        protected PingApiOperationBase(string serviceName)
        {
            ServiceName = serviceName;
            Parameters = new List<KeyValuePair<string, object>>();
        }

        public T MakeCall<T>()
            where T : ClientResponse, new()
        {
            var client = new RestClient(ApiUri);
            var request = new RestRequest(ApiFormat, Method.GET);
            foreach (var parameter in Parameters)
            {
                request.AddParameter(parameter.Key, parameter.Value);
            }
            

            var response = client.Execute<T>(request);

            if (response.ResponseStatus == ResponseStatus.Error)
            {
                return null;
            }

            var result = response.Data;
            result.StatusCode = response.StatusCode;

            return result;
        }

        public abstract bool IsAlive();
    }
}